package com.stylefeng.guns.modular.huamao.util;



import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.request.GetFileLocalRequest;
import com.qcloud.cos.request.UploadFileRequest;
import com.qcloud.cos.sign.Credentials;


public class UploadUtil {
    static long appId = 1256477325;
    static String secretId = "AKIDeFhKVaaIuKUlx0PNm5lT1OPJF7oMc8PU";
    static String secretKey = "3Kix6B5pNoCPVTGrX6B9wojbK1e7TxOi";
    static String bucketName = "huamao";

    /**
     * 上传文件
     * https://cloud.tencent.com/document/product/436/6273
     * @param fileName  文件名
     * @param contentBufer  通过内存上传的buffer内容
     * @return
     */

    public static String upload(String fileName,byte[] contentBufer) {
        // 初始化秘钥信息
        Credentials cred = new Credentials(appId, secretId, secretKey);
        // 初始化客户端配置
        ClientConfig clientConfig = new ClientConfig();
        clientConfig.setRegion("bj");
        // 初始化cosClient
        COSClient cosClient = new COSClient(clientConfig, cred);
        UploadFileRequest uploadFileRequest = new UploadFileRequest(bucketName,fileName,contentBufer);
        String uploadFileRet = cosClient.uploadFile(uploadFileRequest);
        cosClient.shutdown();
        JSONObject jsonObject = JSON.parseObject(uploadFileRet);
        String access_url = (String)((JSONObject) jsonObject.get("data")).get("access_url");
        return access_url;
    }

    /**
     *
     */
    public String downLoad(String cosFilePath){
        // 初始化秘钥信息
        Credentials cred = new Credentials(appId, secretId, secretKey);
        // 初始化客户端配置
        ClientConfig clientConfig = new ClientConfig();
        clientConfig.setRegion("bj");
        // 初始化cosClient
        COSClient cosClient = new COSClient(clientConfig, cred);
        String localPathDown = "d:/test111.png";
        GetFileLocalRequest getFileLocalRequest =
                new GetFileLocalRequest(bucketName, cosFilePath, localPathDown);
        getFileLocalRequest.setUseCDN(false);
        String getFileResult = cosClient.getFileLocal(getFileLocalRequest);
        cosClient.shutdown();
        return  getFileResult;
    }



}
